/**
  * 活动中心
  */
module game {
    export class ActivityCenterMediator extends BaseMediator {
        public static NAME: string = "ActivityCenterMediator";
        private gameType: string = "";
        public constructor(viewComponent: any = null) {
            super(ActivityCenterMediator.NAME, viewComponent);
        }

        public listNotificationInterests(): Array<any> {
            return [
                PanelNotify.HALL.STAGE_RESIZE,
                PanelNotify.HALL.OPEN_ACTIVITY_CENTER,
                PanelNotify.HALL.CLOSE_ACTIVITY_CENTER
            ];
        }
        private panel: ActivityCenterPanel;
        public handleNotification(notification: puremvc.INotification): void {
            this.gameType = notification.getBody();
            switch (notification.getName()) {
                case PanelNotify.HALL.STAGE_RESIZE:
                    if (this.panel) {
                        this.panel.width = GameConfig.curWidth()
                        this.panel.height = GameConfig.curHeight()
                    }
                    break;
                case PanelNotify.HALL.OPEN_ACTIVITY_CENTER: {
                    this.panel = null;
                    this.panel = new ActivityCenterPanel();
                    this.showUI(this.panel, 2, 1, true);
                    break;
                }
                case PanelNotify.HALL.CLOSE_ACTIVITY_CENTER: {
                    egret.clearInterval(this.interval);
                    if (this.timer) {
                        this.timer.stop();
                    }
                    this.closePanel(0);
                    break;
                }
            }
        }

        /**
         * 初始化面板ui
         */
        public initUI(): void {
            this.panel.closeBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.closeButtonClick, this);
            this.panel.qiandaoBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.typeClick, this);
            this.panel.zaixianBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.typeClick, this);
            this.panel.lingquguize.addEventListener(egret.TouchEvent.TOUCH_TAP, this.guizeClick, this);
            this.panel.lingjiang_1.addEventListener(egret.TouchEvent.TOUCH_TAP, this.lingjiangClick, this);
            this.panel.lingjiang_2.addEventListener(egret.TouchEvent.TOUCH_TAP, this.lingjiangClick, this);
            this.panel.lingjiang_3.addEventListener(egret.TouchEvent.TOUCH_TAP, this.lingjiangClick, this);
            this.panel.lingjiang_4.addEventListener(egret.TouchEvent.TOUCH_TAP, this.lingjiangClick, this);
            this.panel.lingjiang_5.addEventListener(egret.TouchEvent.TOUCH_TAP, this.lingjiangClick, this);
            this.panel.lingjiang_6.addEventListener(egret.TouchEvent.TOUCH_TAP, this.lingjiangClick, this);
            this.panel.lingjiang_7.addEventListener(egret.TouchEvent.TOUCH_TAP, this.lingjiangClick, this);

            this.panel.baoxiang1.addEventListener(egret.TouchEvent.TOUCH_TAP, this.lingjiang2Click, this);
            this.panel.baoxiang2.addEventListener(egret.TouchEvent.TOUCH_TAP, this.lingjiang2Click, this);
            this.panel.baoxiang3.addEventListener(egret.TouchEvent.TOUCH_TAP, this.lingjiang2Click, this);
            this.panel.baoxiang4.addEventListener(egret.TouchEvent.TOUCH_TAP, this.lingjiang2Click, this);
            this.panel.baoxiang5.addEventListener(egret.TouchEvent.TOUCH_TAP, this.lingjiang2Click, this);
            this.panel.baoxiang6.addEventListener(egret.TouchEvent.TOUCH_TAP, this.lingjiang2Click, this);
            this.panel.baoxiang7.addEventListener(egret.TouchEvent.TOUCH_TAP, this.lingjiang2Click, this);
            this.panel.baoxiang8.addEventListener(egret.TouchEvent.TOUCH_TAP, this.lingjiang2Click, this);
            this.panel.baoxiang9.addEventListener(egret.TouchEvent.TOUCH_TAP, this.lingjiang2Click, this);
        }

        /**
         * 初始化面板数据
         */

        public initData(): void {
            //初始化各个子界面的下拉多选栏选项
            this.typeClick(null)
        }
        private closeButtonClick(event: egret.TouchEvent): void {
            egret.clearInterval(this.interval);
            if (this.timer) {
                this.timer.stop();
            }
            SoundManage.startAnniuBtnLoad();
            this.closePanel(1);
        }

        //切换标签页
        private typeClick(event: egret.TouchEvent) {
            this.panel.qiandaoBtn.touchEnabled = true
            this.panel.zaixianBtn.touchEnabled = true

            this.panel.qiandaoBtn.icon = "activity_qd_s"
            this.panel.zaixianBtn.icon = "activity_zxjl_s"

            this.panel.qiandao_vive.visible = false
            this.panel.zaixian_vive.visible = false

            if (event == null || event.currentTarget == this.panel.qiandaoBtn) {
                this.panel.qiandaoBtn.touchEnabled = false
                this.panel.qiandaoBtn.icon = "activity_qd"
                this.panel.qiandao_vive.visible = true
                this.qiandaoClick();
            } else if (event.currentTarget == this.panel.zaixianBtn) {
                this.panel.zaixianBtn.touchEnabled = false
                this.panel.zaixianBtn.icon = "activity_zxjl"
                this.panel.zaixian_vive.visible = true
                this.zaixianClick()
            }
        }
        //点击签到活动规则
        private guizeClick() {
            var text = "1.活动时间：自注册日起7天结束。\r\r2.活动详情：每日登录可领取红包。\r\r3.领取规则：昨日下注越高，当日领取红包越大，积分越高\r\r4.补签规则：每次登录只能依次签到，例：若第二天未签到，第三天登录只能补签第二天，依次类推"
            Global.tipShow(text)
        }
        //查询签到奖励
        private qiandaoClick() {
            egret.clearInterval(this.interval);
            if (this.timer) {
                this.timer.stop();
            }
            var time = Math.floor(Global.getCurrTimeLong() / 1000)
            var signature = Global.getSynLoginKey(time)
            signature = signature.toUpperCase()
            var request = new egret.HttpRequest();
            request.responseType = egret.HttpResponseType.TEXT;
            request.open(InstructionsEnum.IP_API + "/ActivityCenter/GetSignInSendCashList?userid=" + GameVO.getVo().dwUserID + "&signature=" + signature + "&time=" + time, egret.HttpMethod.POST);
            request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            request.addEventListener(egret.Event.COMPLETE, (event: egret.Event) => {
                EffectUtils.hideWaritPanel()
                try {
                    var request = <egret.HttpRequest>event.currentTarget;
                    var obj = JSON.parse(request.response)
                    if (obj.code == 0) {
                        this.showQianDaoView(obj);
                    } else {
                        Global.tipShow(obj.mess)
                    }
                } catch (err) {
                    EffectUtils.textFadeAway("数据包异常，无法解析!")
                }
            }, this);
            request.addEventListener(egret.IOErrorEvent.IO_ERROR, () => {
                EffectUtils.hideWaritPanel()
                Global.tipShow("网络请求失败，请稍后重试!")
            }, this);
            EffectUtils.showWaritPanel()
            request.send();
        }
        //显示签到界面
        private SignInSendCashList = [];//我的签到进度
        private UserReceivedList = [];//其他玩家签到公告
        private showQianDaoView(obj: Object) {
            this.SignInSendCashList = obj["data"]["SignInSendCashList"];
            this.UserReceivedList = obj["data"]["UserReceivedList"];
            for (var i = 0; i < this.SignInSendCashList.length; i++) {
                var data = this.SignInSendCashList[i];
                var SignInID = data["SignInID"]//1-7天ID
                var IsReceived = data["IsReceived"] //是否已领取
                if (IsReceived == false) {
                    this.panel["money_" + SignInID].text = "￥???元"
                    this.panel["status_" + SignInID].visible = false;
                } else {
                    this.panel["money_" + SignInID].text = data["Amount"] + "元"
                    this.panel["status_" + SignInID].visible = true;
                }
                this.panel["lingjiang_" + SignInID].name = SignInID + ""
            }
            if (this.UserReceivedList && this.UserReceivedList.length != 0) {
                this.showNotice();
            }
        }
        //点击领签到奖
        private lingjiangClick(eve: egret.TouchEvent) {
            EffectUtils.playDim(eve.currentTarget)
            var name = eve.currentTarget.name;
            var IsReceived = null //是否已领取
            var IsCanRecived = null//是否可以领取
            for (var i = 0; i < this.SignInSendCashList.length; i++) {
                if (name == this.SignInSendCashList[i]["SignInID"]) {
                    IsReceived = this.SignInSendCashList[i]["IsReceived"]
                    IsCanRecived = this.SignInSendCashList[i]["IsCanRecived"]
                    break;
                }
            }

            if (IsReceived === true) {
                EffectUtils.textFadeAway("已领取奖励，不能重复领取。")
                return;
            } else {
                if (IsCanRecived === false) {
                    EffectUtils.textFadeAway("签到时间未到，您还不能领取奖励。")
                    return;
                } else {
                    var time = Math.floor(Global.getCurrTimeLong() / 1000)
                    var signature = Global.getSynLoginKey(time)
                    signature = signature.toUpperCase()
                    var request = new egret.HttpRequest();
                    request.responseType = egret.HttpResponseType.TEXT;
                    request.open(InstructionsEnum.IP_API + "/ActivityCenter/H5UserReceivedSignInSendCash?userid=" + GameVO.getVo().dwUserID + "&signature=" + signature + "&time=" + time, egret.HttpMethod.POST);
                    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                    request.addEventListener(egret.Event.COMPLETE, (event: egret.Event) => {
                        EffectUtils.hideWaritPanel()
                        try {
                            var request = <egret.HttpRequest>event.currentTarget;
                            var obj = JSON.parse(request.response)
                            if (obj.code == 0) {
                                this.qiandaoClick();
                                EffectUtils.textFadeAway("领取成功!")
                                var t = egret.setTimeout(() => {//刷新大厅金币
                                    game.AppFacade.instance.sendNotification(PanelNotify.HALL.FIND_USER_MONEY)
                                    egret.clearTimeout(t)
                                }, this, 500)
                            } else {
                                Global.tipShow(obj.mess)
                            }
                        } catch (err) {
                            EffectUtils.textFadeAway("数据包异常，无法解析!")
                        }
                    }, this);
                    request.addEventListener(egret.IOErrorEvent.IO_ERROR, () => {
                        EffectUtils.hideWaritPanel()
                        Global.tipShow("网络请求失败，请稍后重试!")
                    }, this);
                    EffectUtils.showWaritPanel()
                    request.send(JSON.stringify({ SignID: Number(name) }));
                }
            }
        }
        private interval = null;
        private textField: egret.TextField
        //显示滚动公告
        private showNotice() {
            if (this.textField && this.panel.qiandao_vive.contains(this.textField)) {
                this.panel.qiandao_vive.removeChild(this.textField)
            }
            this.textField = new egret.TextField();
            this.textField.x = 350;
            this.textField.y = 510;
            this.textField.width = 660;
            this.textField.height = 60;
            this.panel.qiandao_vive.addChild(this.textField)
            var thisBack = this;
            var i = 0;
            var fun1 = function (arr) {
                egret.clearInterval(thisBack.interval);
                thisBack.textField.textFlow = arr;
                thisBack.textField.scrollRect = new egret.Rectangle(0, -60, 660, 60);
                thisBack.interval = egret.setInterval(function () {
                    var myRectangle: egret.Rectangle = thisBack.textField.scrollRect;
                    myRectangle.y += 1;
                    if (myRectangle.y > thisBack.textField.height) {
                        myRectangle.y = -60;
                        egret.clearInterval(thisBack.interval);
                        fun2();
                    }
                    thisBack.textField.scrollRect = myRectangle;
                }, this, 30);
            }
            var fun2 = function () {
                var UsreName = thisBack.UserReceivedList[i]["UsreName"]
                var ReceivedDay = thisBack.UserReceivedList[i]["ReceivedDay"]
                var Amount = thisBack.UserReceivedList[i]["Amount"]
                var arr = [
                    { text: "恭喜 ", style: { textColor: 0xDDC492, fontFamily: "Microsoft YaHei" } },
                    { text: UsreName, style: { textColor: 0x33A1F4, fontFamily: "Microsoft YaHei" } },
                    { text: ' 在 ', style: { textColor: 0xDDC492, fontFamily: "Microsoft YaHei" } },
                    { text: "第" + ReceivedDay + "天 ", style: { textColor: 0x8CEF40, fontFamily: "Microsoft YaHei" } },
                    { text: '获得 ', style: { textColor: 0xDDC492, fontFamily: "Microsoft YaHei" } },
                    { text: Amount + "元", style: { textColor: 0xF75151, fontFamily: "Microsoft YaHei" } }
                ]
                fun1(arr)
                i++
                if (i >= thisBack.UserReceivedList.length) {
                    i = 0
                }
            }
            fun2()
        }


        //查询在线奖励
        private timer: egret.Timer = null;
        private zaixianClick() {
            egret.clearInterval(this.interval);
            if (this.timer) {
                this.timer.stop();
            }
            if (this.timer) {
                this.timer.stop();
            }
            var time = Math.floor(Global.getCurrTimeLong() / 1000)
            var signature = Global.getSynLoginKey(time)
            signature = signature.toUpperCase()
            var request = new egret.HttpRequest();
            request.responseType = egret.HttpResponseType.TEXT;
            request.open(InstructionsEnum.IP_API + "/gameinfo/ShowOnlineTimeRewards?uid=" + GameVO.getVo().dwUserID + "&signature=" + signature + "&time=" + time, egret.HttpMethod.GET);
            request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            request.addEventListener(egret.Event.COMPLETE, (event: egret.Event) => {
                EffectUtils.hideWaritPanel()
                try {
                    var request = <egret.HttpRequest>event.currentTarget;
                    var obj = JSON.parse(request.response)
                    if (obj.Success == 0) {
                        this.showZaiXian(obj);
                    } else {
                        Global.tipShow(obj.msg)
                    }
                } catch (err) {
                    EffectUtils.textFadeAway("数据包异常，无法解析!")
                }
            }, this);
            request.addEventListener(egret.IOErrorEvent.IO_ERROR, () => {
                EffectUtils.hideWaritPanel()
                Global.tipShow("网络请求失败，请稍后重试!")
            }, this);
            EffectUtils.showWaritPanel()
            request.send();
        }
        //显示在线奖励
        private showZaiXian(obj: any) {
            var data = obj["Data"]
            var timeInterval: Array<any> = data["timeInterval"];//可领取的时间段
            var lstTimeIntervalPickedUp: Array<any> = data["lstTimeIntervalPickedUp"];//领奖进度
            for (let i = 0; i < timeInterval.length; i++) {
                this.panel["baoxiang" + (i + 1)].label = timeInterval[i] + ""
            }
            var n = 0
            for (var key in lstTimeIntervalPickedUp) {
                var val = lstTimeIntervalPickedUp[key]
                this.panel["baoxiang" + key].touchEnabled = false
                if (val == 1) {
                    n++
                    this.panel["baoxiang" + key].icon = "activity_bx3"
                } else {
                    this.panel["baoxiang" + key].icon = "activity_bx1"
                }
            }

            this.panel.jindutiao.value = ((n - 1) < 0 ? 0 : (n - 1))
            var nextCountdown = data["nextCountdown"];//下次领取的倒计时
            var totalRewardsScore = data["totalRewardsScore"];//已获得总奖励
            this.panel.leijilingqu.text = totalRewardsScore/100 + "元";
            this.panel.xiacilingqu.text = Global.s_to_hs(nextCountdown);
            if (nextCountdown == 0) {
                this.showNextBaoXiang();
            } else if (nextCountdown > 0) {
                var num = nextCountdown
                this.timer = new egret.Timer(1000, nextCountdown + 1);
                this.timer.addEventListener(egret.TimerEvent.TIMER, () => {
                    this.panel.xiacilingqu.text = Global.s_to_hs((num--));
                }, this);
                this.timer.addEventListener(egret.TimerEvent.TIMER_COMPLETE, this.showNextBaoXiang, this);
                this.timer.start();
            }

        }
        //亮起下一个可以点的宝箱
        private showNextBaoXiang() {
            this.panel.xiacilingqu.text = "0";
            for (var i = 1; i < 10; i++) {
                if (this.panel["baoxiang" + i].icon == "activity_bx1") {
                    this.panel["baoxiang" + i].icon = "activity_bx2"
                    this.panel["baoxiang" + i].touchEnabled = true
                    this.panel.jindutiao.value = i - 1;
                    break;
                }
            }
        }
        //点击领在线奖
        private lingjiang2Click(eve: egret.TouchEvent) {
            EffectUtils.playDim(eve.currentTarget)
            var name = eve.currentTarget.name;

            var time = Math.floor(Global.getCurrTimeLong() / 1000)
            var signature = Global.getSynLoginKey(time)
            signature = signature.toUpperCase()
            var request = new egret.HttpRequest();
            request.responseType = egret.HttpResponseType.TEXT;
            request.open(InstructionsEnum.IP_API + "/gameinfo/ObtainOnlineTimeRewards?userid=" + GameVO.getVo().dwUserID + "&signature=" + signature + "&time=" + time, egret.HttpMethod.POST);
            request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            request.addEventListener(egret.Event.COMPLETE, (event: egret.Event) => {
                EffectUtils.hideWaritPanel()
                try {
                    var request = <egret.HttpRequest>event.currentTarget;
                    var obj = JSON.parse(request.response)
                    if (obj.Success == 0) {
                        this.zaixianClick();
                        EffectUtils.textFadeAway("领取成功!")
                        var t = egret.setTimeout(() => {//刷新大厅金币
                            game.AppFacade.instance.sendNotification(PanelNotify.HALL.FIND_USER_MONEY)
                            egret.clearTimeout(t)
                        }, this, 500)
                    } else {
                        Global.tipShow(obj.Msg)
                    }
                } catch (err) {
                    EffectUtils.textFadeAway("数据包异常，无法解析!")
                }
            }, this);
            request.addEventListener(egret.IOErrorEvent.IO_ERROR, () => {
                EffectUtils.hideWaritPanel()
                Global.tipShow("网络请求失败，请稍后重试!")
            }, this);
            EffectUtils.showWaritPanel()
            request.send("uid=" + GameVO.getVo().dwUserID + "&level=" + Number(name));
        }
    }
}
